import { PlusOutlined, DeleteOutlined, RedoOutlined } from '@ant-design/icons';
import { Button, message, Divider, Modal, Input } from 'antd';
import React, { useState, useRef } from 'react';
import { history } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { queryCoachAndSaleList, batchRemoveEmployee, batchResetPwd, resetPwd } from './service';
import { HasPermission } from '@/components/AuthComponent/HasPermission';
const AuthButton = HasPermission(Button);
const AuthDivider = HasPermission(Divider);

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async selectedRows => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  let ids = selectedRows.map(row => row.userId)
  try {
    let result = await batchRemoveEmployee(ids);
    hide();
    if (result.code == 0) {
      message.success('删除成功，即将刷新');
      return true;
    } else {
      message.error(result.message);
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 * 批量重置密码
 * @param {*} selectedRows 
 */
const handleResetPwd = async selectedRows => {
  const hide = message.loading('正在重置');
  if (!selectedRows) return true;
  let ids = selectedRows.map(row => row.userId)
  try {
    let result = await batchResetPwd(ids);
    hide();
    if (result.code == 0) {
      message.success('重置成功，即将刷新');
      return true;
    } else {
      message.error(result.message);
      return false;
    }
  } catch (error) {
    hide();
    message.error('重置失败，请重试');
    return false;
  }
};





const List = props => {
  const actionRef = useRef();
  const [visible, setVisible] = useState(false);
  const [password, setPassword] = useState('');
  const [currentUser, setCurrentUser] = useState(null);
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '手机号',
      dataIndex: 'mobile'
    },
    {
      title: '地址',
      dataIndex: 'province',
      hideInSearch: true,
      render: (text, record) => <>{record.province || ""}{record.city || ""}{record.district || ""}</>
    },
    {
      title: '是否允许登录',
      dataIndex: 'allowLogin',
      hideInSearch: true,
      valueEnum: {
        1: {
          text: '允许',
          status: 'Success',
        },
        2: {
          text: '不允许',
          status: 'Error',
        },
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: {
        0: {
          text: '禁用',
          status: 'Error',
        },
        1: {
          text: '正常',
          status: 'Success',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          {/* <AuthButton auth={[`employee:update`]} type="link"  onClick={() => goToDetail(record)}>详情</AuthButton>
            <AuthDivider auth={['employee:detail',`employee:update`]} type="vertical"></AuthDivider> */}
          <AuthButton auth={[`employee:update`]} type="link" onClick={() => goToEdit(record)}>编辑</AuthButton>
          <AuthDivider auth={['employee:pwd', `employee:update`]} type="vertical"></AuthDivider>
          <AuthButton auth={[`employee:pwd`]} type="link" onClick={() => {
            setVisible(true);
            setCurrentUser(record);
          }}>设置密码</AuthButton>
        </>
      ),
    },
  ];

  /**
  * 新增
  * @param {*} async 
  */
  const goToSave = async => {
    history.push(`/employee/list/save`);
  };

  /**
   * 编辑
   * @param {*} record 
   */
  const goToEdit = async record => {
    history.push(`/employee/list/update/${record.userId}`);
  };

  const goToDetail = (record) => {
    history.push(`/employee/list/detail/${record.userId}`);
  }

  const handleResetSinglePwd = async () => {
    const reg = /(?!^\d{6,18}$)(?!^[a-zA-Z]{6,18}$)^[0-9a-zA-z]{6,18}$/;
    if (!reg.test(password)) {
      message.warn('密码格式不正确');
      return;
    }
    const hide = message.loading('正在设置密码');
    try {
      let result = await resetPwd({
        userId: currentUser?.userId,
        password: password,
      });
      hide();
      if (result.code == 0) {
        message.success('设置成功，即将刷新');
        setVisible(false);
        setPassword('');
        setCurrentUser(null);
        return true;
      } else {
        message.error(result.message);
        return false;
      }
    } catch (error) {
      console.log('error>>',error)
      hide();
      message.error('设置失败，请重试');
      return false;
    }
  };
  return (
    <PageHeaderWrapper>
      <ProTable
        actionRef={actionRef}
        rowKey="userId"
        toolBarRender={(action, { selectedRows }) => [
          <AuthButton auth={[`employee:add`]} type="primary" icon={<PlusOutlined />} onClick={() => goToSave()}>新增</AuthButton>,
          <AuthButton auth={[`employee:batch:delete`]} onClick={() => handleRemove(selectedRows)} danger>批量删除 <DeleteOutlined /></AuthButton>,
          // <AuthButton auth={[`employee:batch:reset:pwd`]} onClick={() => handleResetPwd(selectedRows)}>重置密码 <RedoOutlined /></AuthButton>
        ]}
        tableAlertRender={({ selectedRowKeys, selectedRows }) => (
          <div>
            已选择{' '}
            <a
              style={{
                fontWeight: 600,
              }}
            >
              {selectedRowKeys.length}
            </a>{' '}
            项
          </div>
        )}
        request={params => {
          let _params = {
            empType: null,
            pageNum: params.current,
            ...params,
          }
          delete _params.current
          return queryCoachAndSaleList(_params)
        }}
        postData={result => result.list}
        columns={columns}
        rowSelection={{}}
      />
      {
        visible && <Modal title="设置密码" visible={visible} onOk={() => {
          handleResetSinglePwd();
        }} onCancel={() => {
          setVisible(false);
          setPassword('');
          setCurrentUser(null);
        }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <span style={{ width: '60px' }}>密码：</span>
            <Input.Password placeholder='请填写密码' onChange={(e) => setPassword(e.target.value)} maxLength={18} minLength={6} />
          </div>
          <span style={{
            marginLeft: '50px',
            fontSize: '12px',
            color: '#d9d9d9'
          }}>请输入6~18数字和字母的组合</span>
        </Modal>
      }
    </PageHeaderWrapper>
  );
};

export default List;
